package com.oocl.task0724.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.oocl.task0724.dao.UserDao;
import com.oocl.task0724.dao.impl.UserDaoImpl;
import com.oocl.task0724.pojo.User;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private UserDao userDao=new UserDaoImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		File repository=new File("/users/zero/");
		DiskFileItemFactory factory=new DiskFileItemFactory(20*1024/*20K*/, repository);
		ServletFileUpload upload=new ServletFileUpload(factory);
		upload.setSizeMax(50*1024);
		
		
		User u=new User();
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem fileItem : items) {
				if( fileItem.isFormField() ){
					String fieldName = fileItem.getFieldName();
					String fieldVal = fileItem.getString( "UTF-8" );
					
					System.out.println( fieldName+" : "+fieldVal );
					
					if( "username".equals(fieldName) ){
						u.setUsername(fieldVal);
					}else if( "salary".equals(fieldName) ){
						u.setSalary( Double.parseDouble(fieldVal) ); //NumberFormatException
					}else if( "birth".equals(fieldName) ){
						u.setBirth( getDateFrom(fieldVal) );//ParseException
					}else if( "sex".equals(fieldName) ){
						u.setIsMale( "male".equalsIgnoreCase(fieldVal) );
					}
				}else{
					System.out.println( fileItem.getName() + "..." + fileItem.getSize() );
					StringBuilder buf=new StringBuilder();
					
					InputStream in = fileItem.getInputStream();
					
					byte[] bs=new byte[in.available()];
					in.read(bs);
					u.setHeadImg( bs );
				}
			}
			userDao.add(u);
			response.sendRedirect("/homework0724/userList");
			
		} catch(NumberFormatException e){
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write("salary need to be a number");
			response.getWriter().write("<br/><h1><a href=\""+ "/homework0724" +"\" >back</a></h1>");
		} 
		catch (FileUploadException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write("birth date format need to be yyyy-MM-dd");
			response.getWriter().write("<br/><h1><a href=\""+ "/homework0724" +"\" >back</a></h1>");
		}
	}

	private Date getDateFrom(String fieldVal) throws ParseException {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		return sdf.parse(fieldVal);
	}

}
